<template>
  <div class="invoice-template">
    <!-- 发票详情部分 -->
    <div class="detail-section">
      <div class="detail-header">
        <div class="header-title">销项发票详情</div>
        <div class="header-info">
          <div class="info-row">
            <span
              >模板名称：{{
                getInvoiceTypeText1(invoiceData.templateName)
              }}</span
            >
            <span>开票日期：{{ invoiceData.invoiceDate }}</span>
          </div>
          <div class="info-row">
            <span
              >发票类型:{{ getInvoiceTypeText(invoiceData.invoiceType) }}</span
            >
            <span>开户银行{{ invoiceData.bankAndNumber }}</span>
            <span>发票代码：{{ invoiceData.invoiceCode }}</span>
          </div>
          <div class="info-row">
            <span>关联凭证：无</span>
            <span>凭证编码：无</span>
          </div>
        </div>
        <div class="header-actions">
          <el-button @click="goBack">返回</el-button>
          <el-button type="primary" @click="handlePrint">打印</el-button>
        </div>
      </div>
    </div>

    <!-- 发票打印预览部分 -->
    <div class="print-section" ref="printArea">
      <div class="electronic-invoice" v-loading="loading">
        <div class="invoice-header">
          <h2>电子发票（{{ getInvoiceTypeText(invoiceData.invoiceType) }}）</h2>
          <div class="invoice-number">
            <div>发票代码：{{ invoiceData.invoiceCode }}</div>
            <div>发票号码：{{ invoiceData.invoiceNumber }}</div>
            <div>开票日期：{{ invoiceData.invoiceDate }}</div>
            <div>附件：1</div>
          </div>
        </div>

        <div class="party-box">
          <div class="party-info">
            <div class="party-title">购买方</div>
            <div class="info-line">
              <span class="label">名称：</span>
              <span class="value">{{ invoiceData.customerName }}</span>
            </div>
            <div class="info-line">
              <span class="label">纳税人识别号：</span>
              <span class="value">{{
                invoiceData.taxpayerIdentification
              }}</span>
            </div>
            <div class="info-line">
              <span class="label">地址、电话：</span>
              <span class="value">{{ invoiceData.address }}</span>
            </div>
            <div class="info-line">
              <span class="label">开户行及账号：</span>
              <span class="value">{{ invoiceData.bankAndNumber }}</span>
            </div>
          </div>
          <div class="party-info">
            <div class="party-title">销售方</div>
            <div class="info-line">
              <span class="label">名称：</span>
              <span class="value">XYZ公司</span>
            </div>
            <div class="info-line">
              <span class="label">纳税人识别号：</span>
              <span class="value">987654321098765</span>
            </div>
            <div class="info-line">
              <span class="label">地址、电话：</span>
              <span class="value">上海市XXX路XXX号 021-XXXXXXX</span>
            </div>
            <div class="info-line">
              <span class="label">开户行及账号：</span>
              <span class="value">工商银行 6000000000000</span>
            </div>
          </div>
        </div>

        <div class="invoice-table">
          <el-table :data="invoiceData.taxItemList" border>
            <el-table-column
              label="货物或应税劳务、服务名称"
              prop="specificationModel"
              min-width="200"
            />
            <el-table-column label="规格型号" prop="taxCode" width="100" />
            <el-table-column label="单位" prop="unit" width="80" />
            <el-table-column label="数量" prop="quantity" width="80" />
            <el-table-column label="单价" prop="uninPrice" width="100" />
            <el-table-column label="金额" prop="amount" width="120" />
            <el-table-column label="税率" prop="taxRate" width="80">
              <template #default="scope"> {{ scope.row.taxRate }}% </template>
            </el-table-column>
            <el-table-column label="税额" prop="taxAmount" width="120" />
            <el-table-column label="税收编码" prop="taxCode" width="120" />
            <el-table-column
              label="计税方法"
              prop="taxCalculationMethod"
              width="120"
            />
          </el-table>
        </div>

        <div class="invoice-summary">
          <div class="total-line">
            <span>合计</span>
            <span class="amount">¥{{ calculateTotal("amount") }}</span>
            <span class="tax">¥{{ calculateTotal("taxAmount") }}</span>
          </div>
          <div class="total-summary">
            <span>价税合计（大写）：</span>
            <span class="amount">{{
              convertToChinese(calculateTotalWithTax())
            }}</span>
            <span class="amount-number"
              >（小写）¥{{ calculateTotalWithTax() }}</span
            >
          </div>
        </div>

        <div class="invoice-remarks">
          <span class="label">备注：</span>
          <span class="value">{{ invoiceData.remark }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.invoice-template {
  padding: 20px;
  background: #f5f7fa;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-header {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.header-info .info-row {
  display: flex;
  margin-bottom: 10px;
  color: #666;
}

.header-info .info-row span {
  margin-right: 40px;
}

.header-actions {
  margin-top: 20px;
  text-align: right;
}

.print-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.electronic-invoice {
  width: 900px;
  margin: 0 auto;
  padding: 30px;
  border: 2px solid #c41230;
}

.invoice-header {
  text-align: center;
  border-bottom: 2px solid #c41230;
  padding-bottom: 15px;
}

.invoice-header h2 {
  color: #c41230;
  font-size: 24px;
  margin-bottom: 20px;
}

.invoice-number {
  display: flex;
  justify-content: space-between;
  color: #333;
}

.party-box {
  display: flex;
  margin: 20px 0;
  border: 1px solid #000;
}

.party-info {
  flex: 1;
  padding: 15px;
  position: relative;
}

.party-info:first-child {
  border-right: 1px solid #000;
}

.party-title {
  position: absolute;
  top: -10px;
  left: 20px;
  background: #fff;
  padding: 0 10px;
  color: #c41230;
}

.info-line {
  margin: 8px 0;
}

.info-line .label {
  color: #666;
  display: inline-block;
  width: 120px;
}

.invoice-table {
  margin: 20px 0;
}

:deep(.el-table) {
  border-color: #000;
}

:deep(.el-table--border) {
  border-color: #000;
}

:deep(.el-table td),
:deep(.el-table th) {
  border-color: #000;
}

.invoice-summary {
  text-align: right;
  margin: 20px 0;
}

.total-line {
  margin-bottom: 10px;
}

.total-line .amount,
.total-line .tax {
  margin-left: 50px;
  color: #c41230;
}

.total-in-words {
  margin: 15px 0;
}

.amount-words {
  font-weight: bold;
  margin: 0 10px;
}

.amount-number {
  color: #c41230;
}

.invoice-remarks {
  border-top: 1px solid #ddd;
  padding-top: 15px;
  margin-top: 20px;
}

@media print {
  .detail-section,
  .header-actions {
    display: none;
  }

  .print-section {
    padding: 0;
  }

  .electronic-invoice {
    border: none;
  }
}
</style>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getInvoice } from "@/api/invoice/invoice";

const route = useRoute();
const router = useRouter();
const loading = ref(true);
const invoiceData = ref({});
const printArea = ref(null);

// 获取发票详情
const getInvoiceDetail = async () => {
  try {
    const response = await getInvoice(route.query.id);
    invoiceData.value = response.data;
    loading.value = false;
  } catch (error) {
    proxy.$modal.msgError("获取发票详情失败");
    loading.value = false;
  }
};

// 金额转中文大写
const convertToChinese = (num) => {
  if (!num) return "零元整";

  const digits = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
  const units = ["", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿"];
  const decimal = ["角", "分"];

  let integer = Math.floor(num);
  let fraction = Math.round((num - integer) * 100);

  let result = "";

  if (integer > 0) {
    let zeroCount = 0;
    for (let i = 0; i < String(integer).length; i++) {
      let n = String(integer)[i];
      let p = String(integer).length - i - 1;

      if (n === "0") {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          result += digits[0];
        }
        zeroCount = 0;
        result += digits[parseInt(n)] + units[p];
      }
    }
    result += "元";
  }

  if (fraction > 0) {
    for (let i = 0; i < decimal.length; i++) {
      let n = Math.floor(fraction / 10);
      fraction = fraction % 10;
      if (n !== 0) {
        result += digits[n] + decimal[i];
      }
    }
  } else {
    result += "整";
  }

  return result;
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 打印功能
const handlePrint = () => {
  window.print();
};

onMounted(() => {
  if (route.query.id) {
    getInvoiceDetail();
  }
});

// 获取发票类型文本
const getInvoiceTypeText = (type) => {
  const typeMap = {
    1: "增值税普通发票",
    2: "增值税专用发票",
    3: "增值税电子普通发票",
    4: "增值税待电子专用发票",
    5: "机动车销售统一发票",
    // 可以根据实际需要添加更多类型
  };
  return typeMap[type] || "增值税普通发票";
};

const getInvoiceTypeText1 = (type) => {
  const typeMap = {
    1: "凭证模板一",
    2: "凭证模板二",
    3: "凭证模板三",
    4: "凭证模板四",
    5: "其他",

    // 可以根据实际需要添加更多类型
  };
  return typeMap[type] || "凭证模板一";
};

// 计算合计金额
const calculateTotal = (field) => {
  if (!invoiceData.value?.taxItemList?.length) return "0.00";
  return invoiceData.value.taxItemList
    .reduce((sum, item) => {
      return sum + (Number(item[field]) || 0);
    }, 0)
    .toFixed(2);
};

// 计算价税合计
const calculateTotalWithTax = () => {
  const amount = Number(calculateTotal("amount"));
  const tax = Number(calculateTotal("taxAmount"));
  return (amount + tax).toFixed(2);
};
</script>
